﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Assignment : System.Web.UI.Page
{
    ILE_Global ileGlobal = new ILE_Global();

    AssignmentsBLL assignmentsLogic = new AssignmentsBLL();
    AssignmentsSubmissionsBLL submissionsLogic = new AssignmentsSubmissionsBLL();

    protected DateTime StartedDateTime
    {
        get
        {
            return (DateTime)ViewState["StartedDateTime"];
        }
        set
        {
            ViewState["StartedDateTime"] = value;
        }
    }

    protected string strQuizSubmission
    {
        get
        {
            return (string)Session["xDocQuizSubmission"];
        }
        set
        {
            Session["xDocQuizSubmission"] = value;
        }
    }

    protected string ShuffledQuestions
    {
        get
        {
            return Session["ShuffledQuestions" + "AID" + AssignmentID.ToString() + "cid" + CourseID.ToString() + "scn" + SectionNumber.ToString()].ToString();
        }
        set
        {
            Session["ShuffledQuestions" + "AID" + AssignmentID.ToString() + "cid" + CourseID.ToString() + "scn" + SectionNumber.ToString()] = value;
        }
    }

    protected int QuizQuestioNumberUserIsOn
    {
        get
        {
            return (int)ViewState["QuizQuestioNumberUserIsOn"];
        }
        set
        {
            ViewState["QuizQuestioNumberUserIsOn"] = value;
        }
    }

    protected int UserID
    {
        get
        {
            return (int)Session["UserID"];
        }
        set
        {
            Session["UserID"] = value;
        }
    }

    protected int AssignmentID
    {
        get
        {
            return (int)ViewState["AssignmentID"];
        }
        set
        {
            ViewState["AssignmentID"] = value;
        }
    }

    protected int CourseID
    {
        get
        {
            return (int)ViewState["CourseID"];
        }
        set
        {
            ViewState["CourseID"] = value;
        }
    }

    protected int SectionNumber
    {
        get
        {
            return (int)ViewState["SectionNumber"];
        }
        set
        {
            ViewState["SectionNumber"] = value;
        }
    }

    protected int StandardID
    {
        get
        {
            return (int)ViewState["StandardID"];
        }
        set
        {
            ViewState["StandardID"] = value;
        }
    }

    protected int Attempt
    {
        get
        {
            return (int)ViewState["Attempt"];
        }
        set
        {
            ViewState["Attempt"] = value;
        }
    }

    protected int questionCounter
    {
        get
        {
            return (int)ViewState["questionCounter"];
        }
        set
        {
            ViewState["questionCounter"] = value;
        }
    }

    protected int EssaySubmissionID
    {
        get
        {
            return (int)Session["EssaySubmissionID "];
        }
        set
        {
            Session["EssaySubmissionID "] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //Response.Expires = 0;
        //Response.Cache.SetNoStore();
        //Response.AppendHeader("Pragma", "no-cache");
        try
        {
            //UsersBLL usersLogic = new UsersBLL();
            //UserID = usersLogic.GetUserByUsername(HttpContext.Current.User.Identity.Name.ToString()).UserID;
            UserID = Convert.ToInt32(Session["UserID"].ToString());

            if (UserID <= 0)
            {
                throw new Exception();
            }

        }
        catch (NullReferenceException ex)
        {
            ileGlobal.RecordError("Assignment.aspx.cs:Page_Load:000", ex, "User Session Ended Unexpectedly", 3);
            FormsAuthentication.SignOut();
            Session.Clear();
            Session.Abandon();
            // *SteveMsg
            string _msg = "Your Session has ended. You have been logged out to prevent errors.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _msg, 2, "MyClasses.aspx");
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("Assignment.aspx.cs:Page_Load:001", ex, "User Session Ended Unexpectedly", 3);
            FormsAuthentication.SignOut();
            Session.Clear();
            Session.Abandon();
            // *SteveMsg
            string _msg = "Your Session has ended. You have been logged out to prevent errors.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _msg, 2, "MyClasses.aspx");
        }

        if (Page.IsPostBack == false)
        {
            CourseID = Convert.ToInt32(Request.QueryString["CourseID"]);
            SectionNumber = Convert.ToInt32(Request.QueryString["SectionNumber"]);
            StandardID = Convert.ToInt32(Request.QueryString["StandardID"]);
            AssignmentID = Convert.ToInt32(Request.QueryString["AssignmentID"]);

            if (CourseID == 0 || SectionNumber == 0 || StandardID == 0 || AssignmentID == 0)
            {
                Response.Redirect("MyClasses.aspx");
                return;
            }

            updateProgress.LinkAssociatedUpdatePanel("UpdatePanel1");
            LoadCourseInfo();
            LoadAssignment();
        }
        else
        {
            Assignments.AssignmentsRow assignment = assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID);

            if (assignment == null)
            {
                // *SteveMsg
                string _msg = "Cannot load the page. You will be redirected to the My Classes page.";
                ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _msg, 2, "MyClasses.aspx");
                return;
            }
            else
            {
                if (assignment.AssignmentType == "Quiz" && assignment.EndDateTime <= DateTime.Now)
                {
                    btnQuizBegin.Enabled = false;
                    btnQuizBegin.ForeColor = System.Drawing.Color.Gray;
                    btnQuizBegin.CssClass = "fancyButtonDisabled";
                    btnQuizBegin.Text = "Past Due...";
                }
            }
        }
    }

    protected void updateProgress_InPage_Load(object sender, EventArgs e)
    {
        //updateProgress_InPage.LinkAssociatedUpdatePanel("UpdatePanel2");
    }

    private void LoadCourseInfo()
    {
        ClassBLL classesLogic = new ClassBLL();
        lblCourseSection.Text = classesLogic.GetCourse(CourseID).Title + " | " + "Sect# " + SectionNumber.ToString();

        //lblStandard.Text =
    }

    private void LoadAssignment()
    {
        string AssignmentType = String.Empty;

        Assignments.AssignmentsRow assignment = assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID);

        if (assignment == null)
        {
            // *SteveMsg
            string _msg = "Cannot load the page. You will be redirected to the My Classes page.";
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _msg, 2, "MyClasses.aspx");
            return;
        }

        lblName.Text = assignment.AssignmentTitle;
        if (assignment.Instruction.Trim() == String.Empty || assignment.Instruction.Trim() == "<br />")
        {
            lblInstructions.Text = "<h4 style='text-align: center;'>No Instructions</h4>";
        }
        else
        {
            lblInstructions.Text = assignment.Instruction;
        }
        lblAssignmentDueDateTime.Text = assignment.EndDateTime.ToString("f");

        PanelInstructions.Visible = true;


        if (assignment.AssignmentType == "Quiz")
        {
            Assignments.Assignments_QuizRow quizAssignment = assignmentsLogic.GetAssignmentQuizByAssignmentID(AssignmentID);

            lblQuizStartDateTime.Text = assignment.StartDateTime.ToString("f");
            lblQuizDueDateTime.Text = assignment.EndDateTime.ToString("f");

            double _remainingMinutes = assignment.EndDateTime.Subtract(DateTime.Now).TotalMinutes;
            if (_remainingMinutes > (60 * 24))
            {
                int Days = (Convert.ToInt32(_remainingMinutes / 60 / 24));
                lblQuizRemainingTime.Text = Days.ToString() + " day(s)";
            }
            else if (_remainingMinutes < (60 * 24) &&
                     _remainingMinutes > 60)
            {
                int Hours = (Convert.ToInt32(_remainingMinutes / 60));
                int Minutes = ((Convert.ToInt32(_remainingMinutes)) % 60);
                lblQuizRemainingTime.Text = Hours.ToString() + " hour(s) " + Minutes.ToString() + " minute(s)";
            }
            else if (_remainingMinutes < 60 && _remainingMinutes > 0)
            {
                int Minutes = ((Convert.ToInt32(_remainingMinutes)) % 60);
                lblQuizRemainingTime.Text = Minutes.ToString() + " minute(s)";
            }
            else
            {
                lblQuizRemainingTime.Text = "Past Due";
            }

            lblQuizNumberOfQuestions.Text = quizAssignment.NumberOfQuestions.ToString();
            lblQuizMaximumNumberOfAttempts.Text = quizAssignment.MaximumAttempts.ToString();

            Assignments.Assignments_Submission_QuizDataTable quizSubmissions =
                submissionsLogic.GetQuizSubmissionsByAssignmentIdAndUserId(AssignmentID, UserID);

            decimal yourHighestGrade = 0;
            foreach (Assignments.Assignments_Submission_QuizRow quizSubmission in quizSubmissions)
            {
                if (quizSubmission.GradePercentage > yourHighestGrade)
                    yourHighestGrade = quizSubmission.GradePercentage;
            }

            lblQuizAttemptsTaken.Text = quizSubmissions.Count.ToString();

            if (assignment.EndDateTime < DateTime.Now)
            {
                if (quizSubmissions.Count == 0)
                    lblQuizYourHighestGrade.Text = "You have missed this assignment.";
                else
                    lblQuizYourHighestGrade.Text = yourHighestGrade.ToString("##0.##") + " %";

                btnQuizBegin.Enabled = false;
                btnQuizBegin.ForeColor = System.Drawing.Color.Gray;
                btnQuizBegin.CssClass = "fancyButtonDisabled";
                btnQuizBegin.Text = "Past Due...";
            }
            else
            {
                if (quizSubmissions.Count == 0)
                    lblQuizYourHighestGrade.Text = "You have not taken this quiz assignment yet.";
                else
                    lblQuizYourHighestGrade.Text = yourHighestGrade.ToString("##0.##") + " %";

                if (Convert.ToInt32(quizSubmissions.Count.ToString()) >= Convert.ToInt32(lblQuizMaximumNumberOfAttempts.Text))
                {
                    btnQuizBegin.Enabled = false;
                    btnQuizBegin.ForeColor = System.Drawing.Color.Gray;
                    btnQuizBegin.CssClass = "fancyButtonDisabled";
                    btnQuizBegin.Text = "No more attempts...";
                }
                else
                {
                    btnQuizBegin.CssClass = "fancyButton";
                    btnQuizBegin.Text = "Begin Quiz";
                    btnQuizBegin.ForeColor = System.Drawing.Color.Black;
                    btnQuizBegin.Enabled = true;
                }
            }

            PanelQuiz.Visible = true;
            PanelEssay.Visible = false;
        }
        else // ESSAY!
        {
            Assignments.Assignments_Submission_EssayRow essaySubmission = submissionsLogic.GetEssaySubmissionByAssignmentIdAndUserId(AssignmentID, UserID);

            if (essaySubmission != null)
            {
                EssaySubmissionID = essaySubmission.EssaySubmissionID;
                if (assignment.EndDateTime < DateTime.Now.AddMinutes(1) || essaySubmission.IsFinal == true)
                {
                    MultiViewEssay.ActiveViewIndex = 1;
                    LoadSubmittedEssay(essaySubmission);
                }
                else
                {
                    EditorEssay.Value = essaySubmission.StudentAnswer.Trim();
                }
            }
            else
            {
                if (assignment.EndDateTime < DateTime.Now.AddMinutes(2))
                {
                    MultiViewEssay.ActiveViewIndex = 1;
                    LoadSubmittedEssay(null);
                }
            }

            PanelQuiz.Visible = false;
            PanelEssay.Visible = true;
        }
    }

    private void LoadSubmittedEssay(Assignments.Assignments_Submission_EssayRow essaySubmission)
    {
        if (essaySubmission != null)
        {
            if (essaySubmission.StudentAnswer != null && essaySubmission.StudentAnswer != "")
            {
                lblEssaySubmitted.Text = essaySubmission.StudentAnswer;
                lblEssaySubmittedDateTime.Text = essaySubmission.SubmittedDateTime.ToString("f");

                if ((!essaySubmission.IsGradeNull()) && essaySubmission.Grade != "")
                {
                    lblEssayGrade.Text = essaySubmission.Grade.ToString();

                    Assignments.Assignments_Submission_Essay_CommentsDataTable essayComments =
                        submissionsLogic.GetEssaySubmissionCommentsByEssaySubmissionID(essaySubmission.EssaySubmissionID);

                    RepeaterEssayGradeComments.DataSource = essayComments.Rows;
                    RepeaterEssayGradeComments.DataBind();

                    PanelEssayGrade.Visible = true;
                }
                else
                {
                    PanelEssayGrade.Visible = false;
                }
            }
            else
            {
                // *SteveMsg
                lblEssaySubmitted.Text = "<h5 style='text-align: center;'>You have not submitted your essay.</h5>";

                lblEssaySubmittedDateTime.Text = "no time";
            }
        }
        else
        {
            // *SteveMsg
            lblEssaySubmitted.Text = "<h5 style='text-align: center;'>You have not submitted your essay.</h5>";

            lblEssaySubmittedDateTime.Text = "no time";
        }

    }

    protected void RepeaterEssayGradeComments_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Assignments.Assignments_Submission_Essay_CommentsRow row = e.Item.DataItem as Assignments.Assignments_Submission_Essay_CommentsRow;

            Label lblInstructor = e.Item.FindControl("lblInstructor") as Label;
            Label lblComment = e.Item.FindControl("lblComment") as Label;
            Label lblCommentDateTime = e.Item.FindControl("lblCommentDateTime") as Label;


            UsersBLL usersLogic = new UsersBLL();
            Users.UsersRow instructor = usersLogic.GetUserByUserID(row.InstructorUserID);
            lblInstructor.Text = instructor.FirstName + " " + instructor.LastName;
            lblComment.Text = row.Comment.ToString();
            lblCommentDateTime.Text = row.TimeStamp.ToString("f");
        }
    }

    #region Quiz



    protected void btnBeginQuiz_Click(object sender, EventArgs e)
    {
        XDocument xDocShuffledQuestions = new XDocument();
        xDocShuffledQuestions.Declaration = new XDeclaration("1.0", "utf-8", "yes");
        xDocShuffledQuestions.Add(new XElement("list"));
        ShuffledQuestions = xDocShuffledQuestions.ToString();

        Assignments.Assignments_Submission_QuizDataTable quizSubmissions =
                submissionsLogic.GetQuizSubmissionsByAssignmentIdAndUserId(AssignmentID, UserID);

        // Prevent Cheating.
        Assignments.Assignments_QuizRow quizAssignment = assignmentsLogic.GetAssignmentQuizByAssignmentID(AssignmentID);
        if (quizSubmissions.Count >= quizAssignment.MaximumAttempts)
        {
            ModalPopupMessage.ShowModalPopup_Redirect("Do Not Cheat", "You thihk you know computer?<br />Your cheating-attempt has been recorded in our system and reported to your instructor.", 2, "http://www.bing.com/");
            return;
        }

        Assignments.AssignmentsRow assignment = assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID);

        if (DateTime.Now > assignment.EndDateTime)
        {
            ModalPopupMessage.ShowModalPopup_Redirect("Do Not Cheat", "You thihk you know computer?<br />Your cheating-attempt has been recorded in our system and reported to your instructor.", 2, "http://www.bing.com/");
            return;
        }
        // End Prevent Cheating

        if (quizSubmissions.Count == 0)
        {
            Attempt = 1;
        }
        else
        {
            Attempt = quizSubmissions[0].Attempts + 1;
        }

        PanelInstructions.Visible = false;
        PopulateQuiz();
        QuizQuestioNumberUserIsOn = 1;
        PopulateQuestionsList();
        LoadQuizQuestion();
        MultiViewQuiz.ActiveViewIndex = 1;
        StartedDateTime = DateTime.Now;
    }


    protected void PopulateQuiz()
    {
        XDocument xDocQuizSubmission = new XDocument();
        xDocQuizSubmission = new XDocument();
        xDocQuizSubmission.Declaration = new XDeclaration("1.0", "utf-8", "yes");

        xDocQuizSubmission.Document.Add(new XElement("quizsubmission",
                                new XAttribute("studentuserid", UserID.ToString()),
                                new XAttribute("assignmentid", AssignmentID.ToString()),
                                new XAttribute("attempt", Attempt.ToString()),
                                    new XElement("questions")));

        XDocument xDocQuizAssignment = new XDocument();
        Assignments.Assignments_QuizRow quizAssignment = assignmentsLogic.GetAssignmentQuizByAssignmentID(AssignmentID);
        xDocQuizAssignment = XDocument.Parse(quizAssignment.QuizAssignment);

        List<XElement> _questions = xDocQuizAssignment.Descendants("question").Where(
                    el => (bool)el.Attribute("excluded") != true).ToList();

        int id = 0;
        foreach (XElement question in _questions)
        {
            id++;
            XElement choices = question.Element("choices");

            List<XElement> _choices = choices.Descendants("choice").ToList();

            foreach (XElement _choice in _choices)
            {
                _choice.Add(new XAttribute("isstudentanswer", "false"));
            }
            xDocQuizSubmission.Element("quizsubmission").Element("questions").Add(
                new XElement("question", new XAttribute("id", id.ToString()),
                                         new XAttribute("learnobjid", question.Attribute("learnobjid").Value.ToString()),
                                         new XAttribute("questionid", question.Attribute("id").Value.ToString()),
                                         new XAttribute("difficulty", question.Attribute("difficulty").Value.ToString()),
                                         new XAttribute("point", question.Attribute("point").Value.ToString()),
                                         new XAttribute("required", question.Attribute("defaultrequired").Value.ToString()),
                    new XElement("questiontext", question.Element("questiontext").Value.ToString()),
                    choices));
        }

        List<XElement> _requiredQuestions = new List<XElement>();
        try
        {
            _requiredQuestions = xDocQuizSubmission.Descendants("question").Where(
                        el => (bool)el.Attribute("required") == true).ToList();
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("Assignment.aspx.cs:PopulateQuiz:001", ex, 5);
        }

        int[] orderArray = new int[quizAssignment.NumberOfQuestions];


        for (int i = 0; _requiredQuestions.Count > i; i++)
        {
            Random rand = new Random(Environment.TickCount);

            int arrayIndex = rand.Next(0, quizAssignment.NumberOfQuestions);
            // Speed Improving Code
            //if (i == _requiredQuestions.Count - 4 && _requiredQuestions.Count >= 20)
            //{

            //}

            if (orderArray[arrayIndex] == 0)
                orderArray[arrayIndex] = Convert.ToInt32(_requiredQuestions[i].Attribute("id").Value);
            else
                i--;
        }

        List<XElement> _nonrequiredQuestions = xDocQuizSubmission.Descendants("question").Where(
                    el => (bool)el.Attribute("required") == false).ToList();

        List<XElement> _randomizedNonrequiredQuestions = new List<XElement>();

        for (int i = 0; i < (quizAssignment.NumberOfQuestions - _requiredQuestions.Count); i++)
        {
            Random rand = new Random(Environment.TickCount);
            int randomNumber = rand.Next(_nonrequiredQuestions.Count - 1);
            _randomizedNonrequiredQuestions.Add(_nonrequiredQuestions[randomNumber]);
            _nonrequiredQuestions.RemoveAt(randomNumber);
        }

        try
        {
            foreach (XElement nonrequiredQuestion in _nonrequiredQuestions)
            {
                xDocQuizSubmission.Descendants("question").Where(
                    el => Convert.ToInt32(el.Attribute("id").Value) == Convert.ToInt32(nonrequiredQuestion.Attribute("id").Value)).Remove();
            }
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("Assignment.aspx.cs:PopulateQuiz:002", ex, 5);
        }

        int _tempCounter = 0;
        for (int i = 0; orderArray.Length > i; i++)
        {
            if (orderArray[i] == 0)
            {
                orderArray[i] = Convert.ToInt32(_randomizedNonrequiredQuestions[_tempCounter].Attribute("id").Value);
                _tempCounter++;
            }
        }

        XDocument xDocShuffledQuestions = XDocument.Parse(ShuffledQuestions);
        try
        {
            for (int i = 0; orderArray.Length > i; i++)
            {
                xDocShuffledQuestions.Element("list").Add(xDocQuizSubmission.Descendants("question").Where(el => (int)el.Attribute("id") == orderArray[i]).First());
            }
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("Assignment.aspx.cs:PopulateQuiz:000", ex, 5);
        }

        strQuizSubmission = xDocQuizSubmission.ToString();
        ShuffledQuestions = xDocShuffledQuestions.ToString();
    }

    protected void PopulateQuestionsList()
    {
        try
        {
            XDocument xDocShuffledQuestions = XDocument.Parse(ShuffledQuestions);

            RepeaterQuestionsList.DataSource = xDocShuffledQuestions.Descendants("question").ToList();
            RepeaterQuestionsList.DataBind();

            ShuffledQuestions = xDocShuffledQuestions.ToString();
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("PopulateQuestionsList:000", ex, 3);
        }
    }


    protected void RepeaterQuestionsList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            XElement row = e.Item.DataItem as XElement;

            LinkButton lnkbtnQuestion = e.Item.FindControl("lnkbtnQuestion") as LinkButton;

            lnkbtnQuestion.Font.Bold = true;
            lnkbtnQuestion.Text = "Q#" + questionCounter.ToString();
            if (QuizQuestioNumberUserIsOn == questionCounter)
            {
                lnkbtnQuestion.Enabled = true;
                lnkbtnQuestion.ForeColor = System.Drawing.Color.Red;
            }
            lnkbtnQuestion.CommandArgument = questionCounter.ToString();
            questionCounter++;
        }
    }

    protected void RepeaterQuestionsList_Load(object sender, EventArgs e)
    {
        questionCounter = 1;
    }

    protected void lnkbtnQuestion_Click(object sender, CommandEventArgs e)
    {
        try
        {
            QuizQuestioNumberUserIsOn = Convert.ToInt32(e.CommandArgument);
            PopulateQuestionsList();
            LoadQuizQuestion();
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("lnkbtnQuestion_Click:000", ex, 3);
        }
    }

    protected void LoadQuizQuestion()
    {
        try
        {
            XDocument xDocShuffledQuestions = XDocument.Parse(ShuffledQuestions);

            if (QuizQuestioNumberUserIsOn == 1)
            {
                btnQuestionPrevious.Visible = false;
            }
            else
            {
                btnQuestionPrevious.Visible = true;
            }

            if (QuizQuestioNumberUserIsOn == xDocShuffledQuestions.Descendants("question").Count())
            {
                btnQuestionNext.Visible = false;
                btnQuizSubmit.Visible = true;
            }
            else
            {
                btnQuestionNext.Visible = true;
                btnQuizSubmit.Visible = false;
            }

            lblQuestionNumber.Text = QuizQuestioNumberUserIsOn.ToString();
            List<XElement> RandomizedQuestions = new List<XElement>();
            foreach (XElement element in xDocShuffledQuestions.Descendants("question"))
            {
                RandomizedQuestions.Add(element);
            }

            lblQuizQuestionText.Text = RandomizedQuestions[QuizQuestioNumberUserIsOn - 1].Element("questiontext").Value.ToString();

            List<XElement> choices = RandomizedQuestions[QuizQuestioNumberUserIsOn - 1].Descendants("choice").ToList();
            List<XElement> randomizedChoices = new List<XElement>();

            Random rand = new Random(Environment.TickCount);

            while (choices.Count > 0)
            {
                int randomNumber = rand.Next(choices.Count);
                if (randomNumber < choices.Count)
                {
                    randomizedChoices.Add(choices[randomNumber]);
                    choices.RemoveAt(randomNumber);
                }
            }

            RepeaterChoices.DataSource = randomizedChoices;
            RepeaterChoices.DataBind();

            ShuffledQuestions = xDocShuffledQuestions.ToString();
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("LoadQuizQuestion:000", ex, 3);
        }
    }

    protected void RepeaterChoices_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            XElement row = e.Item.DataItem as XElement;

            CheckBox chkboxChoice = e.Item.FindControl("chkboxChoice") as CheckBox;
            if (row.Attribute("isstudentanswer").Value == "true")
                chkboxChoice.Checked = true;

            chkboxChoice.Text = row.Value;
        }
    }

    protected void btnQuestionPrevious_Click(object sender, EventArgs e)
    {
        QuizQuestioNumberUserIsOn--;
        PopulateQuestionsList();
        LoadQuizQuestion();
    }

    protected void btnQuestionNext_Click(object sender, EventArgs e)
    {
        QuizQuestioNumberUserIsOn = QuizQuestioNumberUserIsOn + 1;
        PopulateQuestionsList();
        LoadQuizQuestion();
    }

    protected void chkboxChoice_CheckedChanged(object sender, EventArgs e)
    {
        XDocument xDocQuizSubmission = XDocument.Parse(strQuizSubmission.ToString());
        XDocument xDocShuffledQuestions = XDocument.Parse(ShuffledQuestions);

        List<XElement> RandomizedQuestions = new List<XElement>();
        foreach (XElement element in xDocShuffledQuestions.Descendants("question"))
        {
            RandomizedQuestions.Add(element);
        }

        if (strQuizSubmission == null || strQuizSubmission == String.Empty)
        {
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "We are Sorry... An unexpected error has occurred. This error has been reported to our system and we will fix it as soon as possible.", 2,
                "Assignment.aspx?AssignmentID=" + AssignmentID.ToString() + "&CourseID=" + CourseID.ToString() + "&SectionNumber=" + SectionNumber.ToString() + "&StandardID=" + StandardID.ToString());
            return;
        }

        XElement question = null;
        try
        {
            question = xDocQuizSubmission.Descendants("question").Where(
                el => (int)el.Attribute("id") == Convert.ToInt32(RandomizedQuestions[QuizQuestioNumberUserIsOn - 1].Attribute("id").Value)).SingleOrDefault();
        }
        catch (Exception ex)
        {
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "We are Sorry... An unexpected error has occurred. This error has been reported to our system and we will fix it as soon as possible.", 2,
                "Assignment.aspx?AssignmentID=" + AssignmentID.ToString() + "&CourseID=" + CourseID.ToString() + "&SectionNumber=" + SectionNumber.ToString() + "&StandardID=" + StandardID.ToString());
            ileGlobal.RecordError("Assignments.apsx.cs:chkboxChoice_CheckedChanged:001", ex, HttpContext.Current.Request.Url.PathAndQuery.ToString() + "<br />" + question.Element("questiontext").Value.ToString(), 4);
        }
        try
        {
            question.Descendants("choice").Where(
                el => (string)el.Value == ((CheckBox)sender).Text).First().SetAttributeValue("isstudentanswer", ((CheckBox)sender).Checked.ToString().ToLower());
        }
        catch (Exception ex)
        {
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "We are Sorry... An unexpected error has occurred. This error has been reported to our system and we will fix it as soon as possible.", 2,
                "Assignment.aspx?AssignmentID=" + AssignmentID.ToString() + "&CourseID=" + CourseID.ToString() + "&SectionNumber=" + SectionNumber.ToString() + "&StandardID=" + StandardID.ToString());
            ileGlobal.RecordError("Assignments.apsx.cs:chkboxChoice_CheckedChanged:002", ex, HttpContext.Current.Request.Url.PathAndQuery.ToString() + "<br />" + question.Element("questiontext").Value.ToString() + "<br />" + question.ToString(), 4);
        }

        try
        {
            RandomizedQuestions[QuizQuestioNumberUserIsOn - 1].Descendants("choice").Where(
                el => (string)el.Value == ((CheckBox)sender).Text).First().SetAttributeValue("isstudentanswer", ((CheckBox)sender).Checked.ToString().ToLower());

            xDocShuffledQuestions.Descendants("question").Where(
                el => el.Attribute("id").Value.ToString() == RandomizedQuestions[QuizQuestioNumberUserIsOn - 1].Attribute("id").Value.ToString()).First().ReplaceWith(RandomizedQuestions[QuizQuestioNumberUserIsOn - 1]);
        }
        catch (Exception ex)
        {
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "We are Sorry... An unexpected error has occurred. This error has been reported to our system and we will fix it as soon as possible.", 2,
                "Assignment.aspx?AssignmentID=" + AssignmentID.ToString() + "&CourseID=" + CourseID.ToString() + "&SectionNumber=" + SectionNumber.ToString() + "&StandardID=" + StandardID.ToString());
            ileGlobal.RecordError("Assignments.apsx.cs:chkboxChoice_CheckedChanged:003", ex, HttpContext.Current.Request.Url.PathAndQuery.ToString() + "<br />" + question.Element("questiontext").Value.ToString(), 4);
        }

        strQuizSubmission = xDocQuizSubmission.ToString();
        ShuffledQuestions = xDocShuffledQuestions.ToString();
    }

    protected void btnQuizSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            XDocument xDocQuizSubmission = XDocument.Parse(strQuizSubmission.ToString());
            if (assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID).EndDateTime <= DateTime.Now.AddMinutes(2))
            {
                // *SteveMsg
                string modalPopupMsg = "We're Sorry, the assignment is past due. Submissions are no longer being accepted.";
                ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 2);
                return;
            }

            // Check if all the questions are answered.
            foreach (XElement question in xDocQuizSubmission.Descendants("question"))
            {
                bool IsAnswered = false;
                foreach (XElement choice in question.Descendants("choice"))
                {
                    try
                    {
                        if (choice.Attribute("isstudentanswer").Value.ToString() == "true")
                        {
                            IsAnswered = true;
                            break;
                        }
                    }
                    catch
                    {
                    }
                }

                if (IsAnswered == false)
                {
                    ModalPopupMessage.ShowModalPopup("ILE Message", "You have not answered all the questions. Please go back and make sure you've answered all of them before you submit!", 2);
                    return;
                }
            }
            strQuizSubmission = xDocQuizSubmission.ToString();
            int quizSubmissionID = submissionsLogic.InsertQuizSubmission(AssignmentID, UserID, CourseID, SectionNumber, StandardID, String.Empty, 0, StartedDateTime);
            if (quizSubmissionID > 0)
            {
                decimal grade = GradeQuizSubmission(quizSubmissionID);
                bool result = submissionsLogic.UpdateQuizSubmission(xDocQuizSubmission.ToString(), grade, quizSubmissionID);
                if (result)
                {
                    // *SteveMsg
                    string modalPopupMsg = "You have successfully submitted your quiz.<br />You received a score of " + grade.ToString("##0.##") + "%";
                    ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", modalPopupMsg, 1, "Assignment.aspx?AssignmentID=" + AssignmentID.ToString() + "&CourseID=" + CourseID.ToString() + "&SectionNumber=" + SectionNumber.ToString() + "&StandardID=" + StandardID.ToString());
                }
                else
                {
                    // *SteveMsg
                    string modalPopupMsg = "Critical Error! Your quiz was not submitted. Please try again.";
                    ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", modalPopupMsg, 2, "Assignment.aspx?AssignmentID=" + AssignmentID.ToString() + "&CourseID=" + CourseID.ToString() + "&SectionNumber=" + SectionNumber.ToString() + "&StandardID=" + StandardID.ToString());
                }
            }
            else
            {
                // *SteveMsg
                string modalPopupMsg = "Critical Error! Your quiz was not submitted. Please try again.";
                ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", modalPopupMsg, 2, "Assignment.aspx?AssignmentID=" + AssignmentID.ToString() + "&CourseID=" + CourseID.ToString() + "&SectionNumber=" + SectionNumber.ToString() + "&StandardID=" + StandardID.ToString());
            }
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("LoadQuizQuestion:000", ex, 3);
        }
    }

    protected decimal GradeQuizSubmission(int QuizSubmissionID)
    {
        try
        {
            XDocument xDocQuizSubmission = XDocument.Parse(strQuizSubmission.ToString());

            int totalPointsAvailable = 0;
            decimal totalPointsStudentGot = 0;

            List<XElement> questions = xDocQuizSubmission.Descendants("question").ToList();

            foreach (XElement question in questions)
            {
                int questionPoint = Convert.ToInt32(question.Attribute("point").Value);
                totalPointsAvailable += questionPoint;
                List<XElement> choices = question.Descendants("choice").ToList();

                int totalCorrectAnswers = 0;
                int totalCorrectStudentAnswers = 0;
                int totalIncorrectStudentAnswers = 0;

                string WrongAnswers = String.Empty;
                foreach (XElement choice in choices)
                {
                    if (Convert.ToBoolean(choice.Attribute("iscorrectanswer").Value) == true)
                    {
                        totalCorrectAnswers++;
                        if (Convert.ToBoolean(choice.Attribute("isstudentanswer").Value) == true)
                        {
                            totalCorrectStudentAnswers++;
                        }
                    }
                    else
                    {
                        if (Convert.ToBoolean(choice.Attribute("isstudentanswer").Value) == true)
                        {
                            totalIncorrectStudentAnswers++;
                            WrongAnswers += choice.Value + ";";
                        }
                    }
                }

                if (totalIncorrectStudentAnswers == 0 && (totalCorrectAnswers == totalCorrectStudentAnswers))
                {
                    RecordQuestionStatistics(QuizSubmissionID, Convert.ToInt32(question.Attribute("learnobjid").Value.ToString()), Convert.ToInt32(question.Attribute("questionid").Value.ToString()), true, null);
                    totalPointsStudentGot += (decimal)questionPoint;
                }
                else
                {
                    RecordQuestionStatistics(QuizSubmissionID, Convert.ToInt32(question.Attribute("learnobjid").Value.ToString()), Convert.ToInt32(question.Attribute("questionid").Value.ToString()), false, WrongAnswers);
                }

                //decimal pointsStudentGot = ((decimal)questionPoint / totalCorrectAnswers) * (totalCorrectStudentAnswers - totalIncorrectStudentAnswers);
                //if (pointsStudentGot > 0)
                //    totalPointsStudentGot += pointsStudentGot;

            }

            decimal gradePercentage = (decimal)totalPointsStudentGot / totalPointsAvailable * 100;

            xDocQuizSubmission.Element("quizsubmission").Add(new XElement("grade",
                                                                new XElement("percentage", gradePercentage.ToString()),
                                                                new XElement("possiblepoints", totalPointsAvailable.ToString()),
                                                                new XElement("earnedpoints", totalPointsStudentGot.ToString())));

            strQuizSubmission = xDocQuizSubmission.ToString();

            return gradePercentage;
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("GradeQuizSubmission:000", ex, 3);
            return 0;
        }
    }

    protected void RecordQuestionStatistics(int QuizSubmissionID, int LearnObjID, int QuestionID, bool isAnsweredCorrectly, string WrongAnswer)
    {
        StatisticsBLL statisticsLogic = new StatisticsBLL();
        UsersBLL usersLogic = new UsersBLL();
        if (LearnObjID != 0)
            statisticsLogic.InsertQuizQuestionStats(QuizSubmissionID, LearnObjID, QuestionID, isAnsweredCorrectly, WrongAnswer);

    }

    #endregion

    #region Essay



    protected void btnEssaySubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (assignmentsLogic.GetAssignmentByAssignmentID(AssignmentID).EndDateTime <= DateTime.Now.AddMinutes(1))
            {
                // *SteveMsg
                string modalPopupMsg = "We're Sorry, the assignment is past due. Submissions are no longer being accepted.";
                ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 2);
                return;
            }

            //string StudentEssay = ileGlobal.Validated(EditorEssay.Value.ToString());
            string StudentEssay = EditorEssay.Value.ToString();
            Assignments.Assignments_Submission_EssayRow essaySubmission = submissionsLogic.GetEssaySubmissionByAssignmentIdAndUserId(AssignmentID, UserID);

            StudentEssay.Trim();

            if (essaySubmission == null)
            {
                EssaySubmissionID = submissionsLogic.InsertEssaySubmission(AssignmentID, UserID, CourseID, SectionNumber, StandardID, StudentEssay, true, DateTime.Now);
                if (EssaySubmissionID != 0)
                {
                    // *SteveMsg
                    string _msg = "Your Essay has been submitted.<br />Thank you.";
                    ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _msg, 1, "Assignment.aspx?CourseID=" + CourseID.ToString() + "&SectionNumber=" + SectionNumber.ToString() + "&StandardID=" + StandardID.ToString() + "&AssignmentID=" + AssignmentID.ToString());
                }
                else
                {
                    // *SteveMsg
                    string _msg = "Failed to submit your Essay. Please try again.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                }
            }
            else
            {
                bool result = submissionsLogic.UpdateEssaySubmission(StudentEssay, true, EssaySubmissionID);
                if (result)
                {
                    // *SteveMsg
                    string _msg = "Your Essay has been submitted.<br />Thank you.";
                    ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", _msg, 1, "Assignment.aspx?CourseID=" + CourseID.ToString() + "&SectionNumber=" + SectionNumber.ToString() + "&StandardID=" + StandardID.ToString() + "&AssignmentID=" + AssignmentID.ToString());
                }
                else
                {
                    // *SteveMsg
                    string _msg = "Failed to submit your Essay. Please try again.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                }
            }
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("btnEssaySubmit_Click:000", ex, 3);
        }
    }

    protected void btnEssaySave_Click(object sender, EventArgs e)
    {
        try
        {
            string StudentEssay = EditorEssay.Value.ToString();
            //string StudentEssay = ileGlobal.Validated(EditorEssay.Value.ToString());
            Assignments.Assignments_Submission_EssayRow essaySubmission = submissionsLogic.GetEssaySubmissionByAssignmentIdAndUserId(AssignmentID, UserID);

            StudentEssay.Trim();
            if (essaySubmission == null)
            {
                EssaySubmissionID = submissionsLogic.InsertEssaySubmission(AssignmentID, UserID, CourseID, SectionNumber, StandardID, StudentEssay, false, DateTime.Now);
                if (EssaySubmissionID != 0)
                {
                    // *SteveMsg
                    string _msg = "Your Essay has been saved.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 1);
                }
                else
                {
                    // *SteveMsg
                    string _msg = "Failed to save your Essay. Please try again.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                }
            }
            else
            {
                bool result = submissionsLogic.UpdateEssaySubmission(StudentEssay, false, EssaySubmissionID);
                if (result)
                {
                    // *SteveMsg
                    string _msg = "Your Essay has been saved.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 1);
                }
                else
                {
                    // *SteveMsg
                    string _msg = "Failed to save your Essay. Please try again.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                }
            }
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("LoadQuizQuestion:000", ex, 3);
        }
    }

    protected void btnEssayAutoSave_Click(object sender, EventArgs e)
    {
        try
        {
            string StudentEssay = EditorEssay.Value.ToString();
            //string StudentEssay = ileGlobal.Validated(EditorEssay.Value.ToString());

            StudentEssay.Trim();
            Assignments.Assignments_Submission_EssayRow essaySubmission = submissionsLogic.GetEssaySubmissionByAssignmentIdAndUserId(AssignmentID, UserID);

            if (essaySubmission == null)
            {
                EssaySubmissionID = submissionsLogic.InsertEssaySubmission(AssignmentID, UserID, CourseID, SectionNumber, StandardID, StudentEssay, false, DateTime.Now);
                if (EssaySubmissionID != 0)
                {
                    // *SteveMsg
                    lblEssayMessage.Text = "<span class='successfulMessage'>Your Essay has been automatically saved at<br />" + DateTime.Now.ToLongTimeString() + ".</span>";
                }
                else
                {
                    lblEssayMessage.Text = "<span class='failedMessage'>Failed to automatically save your essay!</span>";
                }
            }
            else
            {
                bool result = submissionsLogic.UpdateEssaySubmission(StudentEssay, false, EssaySubmissionID);
                if (result)
                {
                    // *SteveMsg
                    lblEssayMessage.Text = "<span class='successfulMessage'>Your Essay has been automatically saved at<br />" + DateTime.Now.ToLongTimeString() + ".</span>";
                }
                else
                {
                    lblEssayMessage.Text = "<span class='failedMessage'>Failed to automatically save your essay!</span>";
                }
            }
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("LoadQuizQuestion:000", ex, 3);
        }
    }
    #endregion

    protected void btnReturnToModule_Click(object sender, EventArgs e)
    {
        Response.Redirect("Standard.aspx?CourseID=" + CourseID.ToString() + "&SectionNumber=" + SectionNumber.ToString() +
            "&StandardID=" + StandardID.ToString());
    }
}
